<template>
  <div class="user-container">
    <el-card>
      <div class="header">
        <h2>用户管理</h2>
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
      </div>

      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="userName" label="用户名称" width="180" />
        <el-table-column prop="deptName" label="所属部门" />
        <el-table-column prop="role" label="角色" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.userId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form">
        <el-form-item label="用户ID" v-if="isEdit">
          <el-input v-model="form.userId" disabled />
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="所属部门" required>
          <el-select v-model="form.deptId" placeholder="请选择部门">
            <el-option
                v-for="dept in departments"
                :key="dept.deptId"
                :label="dept.deptName"
                :value="dept.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="form.pwd" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getUsers,
  addUser,
  updateUser,
  deleteUser
} from '@/api/users';
import { getDepartments } from '@/api/departments';

export default {
  setup() {
    const loading = ref(false);
    const tableData = ref([]);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增用户');
    const form = ref({
      userId: '',
      userName: '',
      deptId: '',
      role: '',
      pwd: '' // 新增密码字段
    });
    const isEdit = ref(false);
    const departments = ref([]);

    // 获取部门列表
    const fetchDepartments = async () => {
      try {
        const res = await getDepartments();
        if (!Array.isArray(res)) {
          throw new Error('API返回的部门数据不是数组格式');
        }
        departments.value = res;
      } catch (error) {
        ElMessage.error('获取部门列表失败: ' + error.message);
      }
    };

    // 获取用户列表
    // const fetchUsers = async () => {
    //   loading.value = true;
    //   try {
    //     const res = await getUsers();
    //     const dataArray = res.data || res; // 可能是 res.data 包含数组
    //     if (!Array.isArray(dataArray)) {
    //       throw new Error('API返回的数据不是数组格式');
    //     }
    //     tableData.value = dataArray.map(item => ({
    //       userId: item.userId,
    //       userName: item.userName,
    //       deptId: item.deptId,
    //       role: item.role
    //     }));
    //   } catch (error) {
    //     ElMessage.error('获取失败: ' + (error.message || '未知错误'));
    //   } finally {
    //     loading.value = false;
    //   }
    // };
    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true;
      try {
        const res = await getUsers();
        const dataArray = Array.isArray(res) ? res : (res.data || []);
        if (!Array.isArray(dataArray)) {
          throw new Error('API返回的用户数据不是数组格式');
        }

        // 获取部门列表
        await fetchDepartments();

        // 将用户数据与部门列表关联，添加deptName属性
        tableData.value = dataArray.map(user => {
          // 在部门列表中查找用户所属部门
          const dept = departments.value.find(d => d.deptId === user.deptId);
          return {
            ...user,
            deptName: dept ? dept.deptName : '未知部门' // 如果找到部门则显示部门名字，否则显示未知
          };
        });
      } catch (error) {
        ElMessage.error('获取失败: ' + (error.message || '未知错误'));
      } finally {
        loading.value = false;
      }
    };

    // 新增用户
    const handleAdd = () => {
      dialogTitle.value = '新增用户';
      isEdit.value = false;
      form.value = {
        userId: '',
        userName: '',
        deptId: departments.value[0]?.deptId || '',
        role: 'user',
        pwd: '' // 初始化密码字段
      };
      dialogVisible.value = true;
    };

    // 编辑用户
    const handleEdit = (row) => {
      dialogTitle.value = '编辑用户';
      isEdit.value = true;
      form.value = { ...row }; // 包含角色字段
      dialogVisible.value = true;
    };

    // 删除用户
    const handleDelete = (userId) => {
      ElMessageBox.confirm('确认删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteUser(userId);
          ElMessage.success('删除成功');
          fetchUsers();
        } catch (error) {
          ElMessage.error('删除失败: ' + error);
        }
      }).catch(() => {});
    };

    // 提交表单
    const handleSubmit = async () => {
      try {
        const payload = {
          userName: form.value.userName,
          deptId: form.value.deptId,
          role: form.value.role,
          pwd: form.value.pwd
        };
        if (isEdit.value) {
          payload.userId = form.value.userId;
          await updateUser(payload);
          ElMessage.success('更新成功');
        } else {
          await addUser(payload);
          ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        fetchUsers();
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败: ' + error : '新增失败: ' + error);
      }
    };

    onMounted(() => {
      fetchUsers();
    });

    return {
      departments,
      isEdit,

      tableData,
      dialogVisible,
      dialogTitle,
      form,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit
    };
  }
};
</script>

<style scoped>
.user-container {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>